<?php declare(strict_types=1);

$di = \application\units\Di::getInstance();

$params = [
    'admin_id'    => $di->auth->id,
    'pid'         => $di->request->params('pid'),
    'name'        => $di->request->params('name'),
    'resource_id' => $di->request->params('resource_id'),
    'status'      => $di->request->params('status'),
];

if ('' == $params['name']) throw new LogicException('角色组名称不能为空');

if ($params['admin_id'] !== null) {
    $roleIds = $di->auth->getChildrenRoleIds($params['admin_id'], true);
} else {
    $roleIds = $di->auth->getChildrenRoleIdsByRoleId(0, false);
}

if (!in_array($params['pid'], $roleIds)) throw new LogicException('上级ID错误');
if (!in_array($params['status'], [0, 1])) throw new LogicException('状态参数不合法');

$has = $di->db->find('select * from admin_role where name=:name', [
    'name' => $params['name']
]);

if ($has) throw new LogicException('角色名称已存在');

try {
    
    $di->db->beginTransaction();
    
    $di->db->execute('insert into admin_role(pid, name, status, update_time, create_time)
              values(:pid, :name, :status, :update_time, :create_time)', [
        'pid'         => $params['pid'],
        'name'        => $params['name'],
        'status'      => $params['status'],
        'update_time' => date('Y-m-d H:i:s'),
        'create_time' => date('Y-m-d H:i:s'),
    ]);
    
    $id                    = $di->db->lastInsertId();
    $params['resource_id'] = array_filter(explode(',', $params['resource_id']));
    
    $bindValue   = [];
    $insertValue = '';
    // 添加角色组菜单
    foreach ($params['resource_id'] as $index => $resourceId) {
        $insertValue                        .= sprintf('(:role_id_%1$d, :resource_id_%1$d, :update_time_%1$d, :create_time_%1$d),', $index);
        $bindValue['role_id_' . $index]     = $id;
        $bindValue['resource_id_' . $index] = $resourceId;
        $bindValue['update_time_' . $index] = date('Y-m-d H:i:s');
        $bindValue['create_time_' . $index] = date('Y-m-d H:i:s');
    }
    
    $stat = $di->db->execute('insert into admin_role_resource_access(role_id, resource_id, update_time, create_time)
                          values ' . trim($insertValue, ','), $bindValue);
    if ($stat->rowCount() <= 0) throw new PDOException('操作失败');
    
    $di->db->commit();
} catch (Exception $e) {
    $di->db->rollback();
    throw $e;
}

return [
    'row' => [
        'id' => $id,
    ],
];